package com.xinqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinqi.bean.Goods;
import com.xinqi.bean.GoodsOrder;
import com.xinqi.common.R;
import com.xinqi.mapper.GoodsOrderMapper;
import com.xinqi.service.GoodsOrderService;
import com.xinqi.service.IGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xin麒
 * @date 2023/2/21 11:03
 */
@Slf4j
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {
    @Autowired
    private IGoodsService goodsService;
    @Resource
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> GOODS_SCRIPT;
    static {
        GOODS_SCRIPT = new DefaultRedisScript<>();
        GOODS_SCRIPT.setLocation(new ClassPathResource("goods.lua"));
        GOODS_SCRIPT.setResultType(Long.class);
    }
    GoodsOrderService proxy;
    @Override
    public R buyOneGoods(Long goodsId, Long userId) {
        Long result = stringRedisTemplate.execute(
                GOODS_SCRIPT,
                Collections.emptyList(),
                goodsId.toString().intern(), userId.toString()
        );

        int r = result.intValue();

        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return R.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setGoodsId(goodsId);
        goodsOrder.setUserId(userId);
        //先丢到队列里面
        orderTasks.add(goodsOrder);

        proxy = (GoodsOrderService)AopContext.currentProxy();
        return R.success("buy one success");
    }
    private static final ExecutorService GOODS_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        GOODS_ORDER_EXECUTOR.submit(new GoodsOrderHandler());
    }
    private BlockingQueue<GoodsOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private class GoodsOrderHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                try {
                    // 1.获取队列中的订单信息
                    GoodsOrder goodsOrder = orderTasks.take();
                    // 2.创建订单
                    handleGoodsOrder(goodsOrder);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }
    private void handleGoodsOrder(GoodsOrder goodsOrder) {
        Long userId = goodsOrder.getUserId();
        // 创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        // 获取锁
        boolean isLock = lock.tryLock();
        // 判断是否获取锁成功
        if(!isLock){
            // 获取锁失败，返回错误或重试
            log.error("不允许重复下单");
            return;
        }
        try {
            // 获取代理对象（事务）
            proxy.createGoodsOrder(goodsOrder);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }
    @Transactional
    public void createGoodsOrder(GoodsOrder goodsOrder) {
        QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsOrder.getGoodsId())
                .eq("user_id", goodsOrder.getUserId());
        GoodsOrder aGoodsOrder = getOne(queryWrapper);
        if (aGoodsOrder != null) {
            log.error("can not get the goods");
            return;
        }

        Goods goods = goodsService.getById(goodsOrder.getGoodsId());

        if (goods == null || goods.getStock() <= 0) {
            log.error("has not any stock");
            return ;
        }//step 1

        boolean success = goodsService.update()
                .setSql("stock = stock - 1")
                .eq("id", goodsOrder.getGoodsId())
                .gt("stock", goods.getStock() / 3)//这里比较前后的数据是否相等，相等就可以修改库存
                .update();//step 2
        if (!success) {
            log.error("has not any stock");
            return ;
        }
        save(goodsOrder);
    }
}